package com.example.software.controller;


import com.example.software.entity.*;

import com.example.software.service.DiagnosisService;
import com.example.software.service.MedicineService;
import com.example.software.service.RecodeService;
import com.example.software.utils.AesEncryptUtils;
import com.example.software.utils.QRCodeGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 通用接口
 */
@RestController
@RequestMapping("/software/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {

    @Autowired
    private RecodeService recodeService;

    @Autowired
    private DiagnosisService diagnosisService;

    @Autowired
    private MedicineService medicineService;



    @PostMapping("/text")
    public MajorthirdVO get_register_list(@RequestBody MajorthirdVO majorthirdVO) {

        System.out.println("text");

        return majorthirdVO;

    }

    @PostMapping("/getMajorFirstsById")
    public FirstMajorEnum get_register_list(@RequestBody FirstMajorEnumVO majorFirst) {


        System.out.println("text2");

        return majorFirst.getMajorFirst();
    }


    //核销挂号预约和医药支付后核销
    @GetMapping("/WriteOff_register")
    @ApiOperation("核销挂号预约")
    public Result WriteOff_register(String cabinetId) throws Exception {

        System.out.println(cabinetId);
        log.info("加密id，：{}", cabinetId);
        //解密加密后的快递柜id
        try {
            cabinetId = AesEncryptUtils.decrypt(cabinetId, "gbcdef0123456789");
        }catch (Exception e) {
//            e.printStackTrace();
            return Result.error("核销失败");
        }
        log.info("解密后的id：{}", cabinetId);

        RecodeEntity entity = new RecodeEntity();
        entity.setId(Long.valueOf(cabinetId));
        entity.setState(4);//改成已核销状态
        recodeService.updateById(entity);

        return Result.success("核销成功");
    }

    @GetMapping("/WriteOff_medicine")
    @ApiOperation("核销药品支付")
    public Result WriteOff_medicine(String cabinetId) throws Exception {

        System.out.println(cabinetId);
        log.info("加密id，：{}", cabinetId);
        //解密加密后的快递柜id
        try {
            cabinetId = AesEncryptUtils.decrypt(cabinetId, "abcdef0123456789"); //两个核销二维码的加密盐不同
        }catch (Exception e) {
//            e.printStackTrace();
            return Result.error("核销失败");
        }
        log.info("解密后的id：{}", cabinetId);

        DiagnosisEntity entity = diagnosisService.getById(Long.valueOf(cabinetId));
        if (entity.getState() == 0) {

            List<MedicineEntity> medicineList = medicineService.listByIds(Arrays.asList(entity.getMedicineId().replace("[","").replace("]","").split(",")));
            DiagnosisEntity diagnosisEntity = new DiagnosisEntity();
            diagnosisEntity.setId(entity.getId());
            diagnosisEntity.setState(1);
            diagnosisService.updateById(diagnosisEntity);

            return Result.success(medicineList,"核销成功");
        }else
        {
            return Result.error("已核销");
        }

    }

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @CrossOrigin
    @ApiOperation("文件上传")
    public Result<String> upload(@RequestBody MultipartFile file) throws IOException {

        String url = material_Util.uploadImage(file);

        return Result.success(url);
    }


    //生成和解析二维码的接口
    @GetMapping("/generate-qr-code")
    @CrossOrigin
    @ApiOperation("生成二维码的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "content", value = "挂号预约id或者是诊断id", required = true),
            @ApiImplicitParam(name = "key", value = "传recode或diagnosis", required = true),
    })
//    public ResponseEntity<FileSystemResource> generateQRCode(@RequestParam String content) throws Exception {
    public Result generateQRCode(@RequestParam String content,
                                                 @RequestParam String key) throws Exception {
        // 生成临时文件路径

//        String filePath = "D:\\springboot_text\\internship-program\\sky-take-out\\sky-common\\src\\main\\resources\\" + System.currentTimeMillis() + ".png";
//
//        filePath = "text.png";

//        QRCodeGenerator qrCodeGenerator = new QRCodeGenerator();
//        // 调用生成器生成二维码并保存到文件
//        String content_aes= AesEncryptUtils.encrypt(content, "abcdef0123456789");   //加密
//        qrCodeGenerator.generateQRCode(content_aes, filePath);
//
//        // 返回生成的二维码图片资源
//
//        FileSystemResource file = new FileSystemResource(new File(filePath));
//        return ResponseEntity.ok().header("Content-Type", "image/png").body(file);

        //base64的传输方式
        String filePath = "D:\\springboot_text\\internship-program\\sky-take-out\\sky-common\\src\\main\\111.png";
        filePath = "text.png";
        QRCodeGenerator qrCodeGenerator = new QRCodeGenerator();

        String content_aes = null;
        if (key.equals("diagnosis")){
            content_aes= AesEncryptUtils.encrypt(content, "abcdef0123456789");   //加密
        }else {
            content_aes= AesEncryptUtils.encrypt(content, "gbcdef0123456789");   //加密
        }

        // 调用生成器生成二维码并保存到文件

        qrCodeGenerator.generateQRCode(content_aes, filePath);


        //将二维码存到oss服务器上并保存到数据库中
        File file = new File(filePath);
        String url = material_Util.uploadImage2(file);

        if (key.equals("recode")){

            RecodeEntity entity = new RecodeEntity();
//            entity.setQrcode(url);

            entity.setQrCode(url);
            entity.setId(Long.valueOf(content));
            recodeService.updateById(entity);

        }else if (key.equals("diagnosis")){

            DiagnosisEntity entity = new DiagnosisEntity();
            entity.setQrCode(url);
            entity.setId(Long.valueOf(content));
            diagnosisService.updateById(entity);

        }

        return Result.success(url);

//        Path path = Paths.get(filePath);
//        Resource resource = new UrlResource(path.toUri());
//        if (resource.exists() || resource.isReadable()) {
//            byte[] bytes = Files.readAllBytes(path);
//            String base64String = Base64.getEncoder().encodeToString(bytes);
//            return ResponseEntity.ok("data:image/jpeg;base64," + base64String);
//        } else {
//            return ResponseEntity.notFound().build();
//        }

    }

//    /**
//     * 文件上传
//     * @param file
//     * @return
//     */
//    @PostMapping("/upload")
//    @ApiOperation("文件上传")
//    public Result<String> upload(MultipartFile file){
//        log.info("文件上传：{}",file);
//
//        try {
//            //原始文件名
//            String originalFilename = file.getOriginalFilename();
//            //截取原始文件名的后缀   dfdfdf.png
//            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
//            //构造新文件名称
//            String objectName = UUID.randomUUID().toString() + extension;
//
//            //文件的请求路径
//            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
//            return Result.success(filePath);
//        } catch (IOException e) {
//            log.error("文件上传失败：{}", e);
//        }
//
//        return Result.error(MessageConstant.UPLOAD_FAILED);
//    }
}
